// wuxing.js
const lunar = require('./lunar')

// 五行属性定义
const WUXING = {
  JIN: { name: '金', color: '金色', season: '秋', direction: '西', organs: '肺、大肠', taste: '辛', emotion: '悲' },
  MU: { name: '木', color: '绿色', season: '春', direction: '东', organs: '肝、胆', taste: '酸', emotion: '怒' },
  SHUI: { name: '水', color: '蓝色', season: '冬', direction: '北', organs: '肾、膀胱', taste: '咸', emotion: '恐' },
  HUO: { name: '火', color: '红色', season: '夏', direction: '南', organs: '心、小肠', taste: '苦', emotion: '喜' },
  TU: { name: '土', color: '黄色', season: '长夏', direction: '中', organs: '脾、胃', taste: '甘', emotion: '思' }
};

// 五行相生关系
const SHENG = {
  JIN: 'SHUI',
  SHUI: 'MU',
  MU: 'HUO',
  HUO: 'TU',
  TU: 'JIN'
}

// 五行相克关系
const KE = {
  JIN: 'MU',
  MU: 'TU',
  TU: 'SHUI',
  SHUI: 'HUO',
  HUO: 'JIN'
}

class WuxingCalculator {
  constructor() {
    this.wuxing = WUXING
    this.sheng = SHENG
    this.ke = KE
  }

  calculate({ birthDate, birthTime, gender }) {
    try {
      // 转换为农历
      const lunarDate = lunar.solarToLunar(birthDate)
      
      // 计算八字
      const bazi = this.calculateBazi(lunarDate, birthTime)
      
      // 计算五行属性
      const wuxing = this.calculateWuxing(bazi)
      
      // 计算五行强度
      const strength = this.calculateStrength(birthDate, birthTime)
      
      // 生成解读
      const interpretation = this.getAnalysis(strength)

      return {
        wuxing,
        strength,
        interpretation,
        bazi
      }
    } catch (error) {
      console.error('五行计算错误:', error)
      throw new Error('五行计算失败')
    }
  }

  calculateBazi(lunarDate, birthTime) {
    const year = lunarDate.year
    const month = lunarDate.month
    const day = lunarDate.day
    const hour = parseInt(birthTime.split(':')[0])

    // 简化版八字计算
    return {
      year: this.getYearWuxing(year),
      month: this.getMonthWuxing(month),
      day: this.getDayWuxing(day),
      hour: this.getHourWuxing(hour)
    }
  }

  getYearWuxing(year) {
    const remainder = year % 5
    const wuxingMap = ['JIN', 'MU', 'SHUI', 'HUO', 'TU']
    return wuxingMap[remainder]
  }

  getMonthWuxing(month) {
    const wuxingMap = ['JIN', 'JIN', 'MU', 'MU', 'SHUI', 'SHUI', 'HUO', 'HUO', 'TU', 'TU', 'JIN', 'JIN']
    return wuxingMap[month - 1]
  }

  getDayWuxing(day) {
    const remainder = day % 5
    const wuxingMap = ['JIN', 'MU', 'SHUI', 'HUO', 'TU']
    return wuxingMap[remainder]
  }

  getHourWuxing(hour) {
    const wuxingMap = ['JIN', 'JIN', 'MU', 'MU', 'SHUI', 'SHUI', 'HUO', 'HUO', 'TU', 'TU', 'JIN', 'JIN']
    return wuxingMap[Math.floor(hour / 2)]
  }

  calculateWuxing(bazi) {
    const counts = {
      JIN: 0,
      MU: 0,
      SHUI: 0,
      HUO: 0,
      TU: 0
    }

    // 统计五行出现次数
    Object.values(bazi).forEach(wuxing => {
      counts[wuxing]++
    })

    // 找出最多的五行
    let maxWuxing = 'JIN'
    let maxCount = counts.JIN

    Object.entries(counts).forEach(([wuxing, count]) => {
      if (count > maxCount) {
        maxWuxing = wuxing
        maxCount = count
      }
    })

    return maxWuxing
  }

  calculateStrength(birthDate, birthTime) {
    // 基础分数
    const baseScore = 20;
    
    // 根据出生日期计算五行强度
    const month = birthDate.getMonth() + 1;
    const hour = parseInt(birthTime.split(':')[0]);
    
    // 季节影响
    const seasonScores = {
      JIN: month >= 8 && month <= 10 ? 30 : 0,
      MU: month >= 2 && month <= 4 ? 30 : 0,
      SHUI: month >= 11 || month === 1 ? 30 : 0,
      HUO: month >= 5 && month <= 7 ? 30 : 0,
      TU: 15 // 土在四季都有一定强度
    };
    
    // 时辰影响
    const timeScores = {
      JIN: (hour >= 15 && hour < 17) || (hour >= 3 && hour < 5) ? 20 : 0,
      MU: (hour >= 5 && hour < 7) || (hour >= 13 && hour < 15) ? 20 : 0,
      SHUI: (hour >= 21 && hour < 23) || (hour >= 1 && hour < 3) ? 20 : 0,
      HUO: (hour >= 11 && hour < 13) || (hour >= 19 && hour < 21) ? 20 : 0,
      TU: (hour >= 7 && hour < 9) || (hour >= 17 && hour < 19) ? 20 : 0
    };
    
    // 计算总强度
    const strengths = {};
    for (const element in this.wuxing) {
      strengths[element] = baseScore + seasonScores[element] + timeScores[element];
    }
    
    // 转换为百分比
    const total = Object.values(strengths).reduce((a, b) => a + b, 0);
    for (const element in strengths) {
      strengths[element] = Math.round((strengths[element] / total) * 100);
    }
    
    return strengths;
  }

  getAnalysis(strengths) {
    // 找出最强和最弱的五行
    const sortedElements = Object.entries(strengths)
      .sort(([, a], [, b]) => b - a)
      .map(([element]) => element);
    
    const strongest = sortedElements[0];
    const weakest = sortedElements[sortedElements.length - 1];
    
    // 生成分析结果
    return {
      attribute: `您的命局以${this.wuxing[strongest].name}为主，${this.wuxing[weakest].name}较弱。`,
      personality: this.getPersonalityAnalysis(strongest, weakest),
      career: this.getCareerAdvice(strongest),
      health: this.getHealthAdvice(strongest, weakest),
      direction: this.wuxing[strongest].direction,
      color: this.wuxing[strongest].color,
      season: this.wuxing[strongest].season,
      organs: this.wuxing[strongest].organs,
      taste: this.wuxing[strongest].taste,
      emotion: this.wuxing[strongest].emotion
    };
  }

  getPersonalityAnalysis(strongest, weakest) {
    const personalityTraits = {
      JIN: '性格刚毅，重视原则，做事有条理，但可能过于固执。',
      MU: '性格开朗，富有创造力，善于表达，但可能情绪波动较大。',
      SHUI: '性格灵活，思维敏捷，适应力强，但可能缺乏主见。',
      HUO: '性格热情，充满活力，领导力强，但可能过于急躁。',
      TU: '性格稳重，踏实可靠，重情重义，但可能过于保守。'
    };
    
    return personalityTraits[strongest];
  }

  getCareerAdvice(strongest) {
    const careerAdvice = {
      JIN: '适合从事金融、法律、管理等工作，善于处理规则和制度。',
      MU: '适合从事创意、设计、教育等工作，善于创新和表达。',
      SHUI: '适合从事研究、咨询、传媒等工作，善于分析和沟通。',
      HUO: '适合从事销售、营销、演艺等工作，善于与人交往。',
      TU: '适合从事农业、建筑、服务等工作，善于实践和协调。'
    };
    
    return careerAdvice[strongest];
  }

  getHealthAdvice(strongest, weakest) {
    const healthAdvice = {
      JIN: '注意呼吸系统保养，适当运动增强体质。',
      MU: '注意肝胆系统保养，保持情绪稳定。',
      SHUI: '注意泌尿系统保养，保持充足睡眠。',
      HUO: '注意心血管系统保养，避免过度劳累。',
      TU: '注意消化系统保养，规律饮食作息。'
    };
    
    return `主要${healthAdvice[strongest]}同时要注意${this.wuxing[weakest].organs}的保养。`;
  }

  getRelationships(strengths) {
    const relationships = [
      {
        title: '相生关系',
        content: '金生水，水生木，木生火，火生土，土生金。相生表示促进、滋养。'
      },
      {
        title: '相克关系',
        content: '金克木，木克土，土克水，水克火，火克金。相克表示制约、平衡。'
      }
    ];
    
    return relationships;
  }
}

module.exports = {
  WuxingCalculator,
  WUXING
}; 